package com.abe.libfitness.main;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.abe.libcore.base.screen.OnHandlerListener;
import com.abe.libcore.utils.CommonUtils;
import com.abe.libfitness.R;
import com.abe.libfitness.R2;
import com.abe.libfitness.base.BaseActivity;
import com.abe.libfitness.main.dialog.MotorDialog;
import com.abe.libfitness.utils.ConstantFitness;
import com.abe.libfitness.utils.SpFitnessHelper;
import com.abe.libfitness.widget.RoundBarChartRenderer;
import com.abe.libquick.utils.NormalUtils;
import com.abe.libquick.utils.quick.EmptyUtils;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.king.view.arcseekbar.ArcSeekBar;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

public class TestActivity extends BaseActivity implements MotorDialog.OnMotorActionListener,
        ArcSeekBar.OnChangeListener, OnHandlerListener {

    private static final int MIN_WEIGHT = 5;//最小力量
    private static final int MAX_WEIGHT = 30;//最大力量
    @BindView(R2.id.item_seek_bar)
    ArcSeekBar itemSeekBar;
    @BindView(R2.id.item_weight)
    TextView itemWeight;
    @BindView(R2.id.item_start_stop)
    ImageView itemStartStop;
    @BindView(R2.id.item_ball_chart)
    LineChart itemBallChart;
    @BindView(R2.id.item_count_chart)
    BarChart itemCountChart;
    boolean isMotorStart;
    private MotorDialog motorDialog;
    //柱状数据
    private List<String> weights;
    private List<BarEntry> countDistances;
    //折线数据
    private List<String> times;
    private List<Entry> distances;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_exercise;
    }

    @Override
    protected void initContent() {
        isMotorStart = true;
        weights = new ArrayList<>();
        countDistances = new ArrayList<>();
        times = new ArrayList<>();
        distances = new ArrayList<>();
        itemSeekBar.setMax(MAX_WEIGHT - MIN_WEIGHT);
        //进度改变监听
        itemSeekBar.setOnChangeListener(this);
        CommonUtils.INSTANCE.log("---------------------------getScale():" + getScale());
        setChartStyle();
        setCountChartStyle();
        getHandler().postDelayed(() -> {
            itemSeekBar.setProgress(0);
            for (int i = 0; i < 20; i++) {
                int move = (int) (new Random().nextDouble() * 400);
                times.add("10-" + i);
                distances.add(new Entry(i, move));
                weights.add("10-" + i);
                countDistances.add(new BarEntry(i, move));
            }
            localEmptyMsg(0x001);
            //localEmptyMsg(0x002);
        }, 500);
    }

    private void setChartStyle() {
        itemBallChart.getDescription().setEnabled(false);
        itemBallChart.setNoDataText("");
        itemBallChart.getAxisRight().setEnabled(false);
        itemBallChart.getAxisLeft().setEnabled(false);
        itemBallChart.getLegend().setEnabled(false);
        itemBallChart.setScaleEnabled(true);
        itemBallChart.setScaleYEnabled(false);
        itemBallChart.setScaleXEnabled(true);
    }

    private void setCountChartStyle() {
        itemCountChart.getDescription().setEnabled(false);
        itemCountChart.setNoDataText("");
        itemCountChart.getAxisRight().setEnabled(false);
        itemCountChart.getAxisLeft().setEnabled(false);
        itemCountChart.getLegend().setEnabled(false);
        itemCountChart.setScaleEnabled(true);
        itemCountChart.setScaleYEnabled(false);
        itemCountChart.setScaleXEnabled(true);
        itemCountChart.setRenderer(new RoundBarChartRenderer(itemCountChart, itemCountChart.getAnimator(),
                itemCountChart.getViewPortHandler()));
    }

    private void refreshBallChart() {
        XAxis xAxis = itemBallChart.getXAxis();
        xAxis.setTextSize(14f);//设置字体大小
        xAxis.setTextColor(Color.WHITE);//设置字体颜色
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//将x轴位于底部
        xAxis.setDrawGridLines(false);//不绘制网格线
        xAxis.setGranularity(1);//间隔1
        //小技巧，通过设置Axis的最小值设置为负值，可以改变距离与Y轴的距离
        xAxis.setAxisMaximum(times.size() - 1 + 0.2f);//设置最小值
        xAxis.setAxisMinimum(-0.2f);//设置最大值
        xAxis.setLabelCount(times.size());//设置数量
        xAxis.setTextSize(8f);
        //自定义样式
        xAxis.setValueFormatter(new ValueFormatter() {

            @Override
            public String getFormattedValue(float value) {
                int pos = (int) value;
                return pos >= times.size() ? "" : times.get(pos);
            }
        });
        int lineColor = getResources().getColor(R.color.color_theme_yellow);
        LineDataSet lineDataSet = new LineDataSet(distances, "");
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSet.setColor(lineColor);
        lineDataSet.setLineWidth(2);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFillColor(lineColor);
        lineDataSet.setFillAlpha(20);
        lineDataSet.setDrawHighlightIndicators(false);
        lineDataSet.setDrawValues(false);
        LineData lineData = new LineData(lineDataSet);
        itemBallChart.setData(lineData);
        int c = SpFitnessHelper.isPortrait() ? 8 : 6;
        if (distances.size() > c) {
            itemBallChart.setVisibleXRange(0, c);
            itemBallChart.moveViewToX(distances.size());
        }
        itemBallChart.invalidate();
    }

    private void refreshCountChart() {
        XAxis xAxis = itemCountChart.getXAxis();
        xAxis.setTextSize(14f);//设置字体大小
        xAxis.setTextColor(Color.WHITE);//设置字体颜色
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//将x轴位于底部
        xAxis.setDrawGridLines(false);//不绘制网格线
        xAxis.setGranularity(1);//间隔1
        //小技巧，通过设置Axis的最小值设置为负值，可以改变距离与Y轴的距离
        xAxis.setAxisMaximum(weights.size() - 1 + 0.2f);//设置最小值
        xAxis.setAxisMinimum(-0.2f);//设置最大值
        xAxis.setLabelCount(weights.size());//设置数量
        xAxis.setTextSize(8f);
        //自定义样式
        xAxis.setValueFormatter(new ValueFormatter() {

            @Override
            public String getFormattedValue(float value) {
                int pos = (int) value;
                return pos >= weights.size() ? "" : weights.get(pos);
            }
        });
        int lineColor = getResources().getColor(R.color.green_light);
        BarDataSet barDataSet = new BarDataSet(countDistances, "");
        barDataSet.setColor(lineColor);
        barDataSet.setHighlightEnabled(false);
        barDataSet.setDrawValues(false);
        BarData barData = new BarData(barDataSet);
        barData.setBarWidth(0.2f);
        itemCountChart.setFitBars(true);
        itemCountChart.setData(barData);
        int c = 8;
        if (countDistances.size() > c) {
            itemCountChart.setVisibleXRange(0, c);
            itemCountChart.moveViewToX(countDistances.size());
        }
        itemCountChart.invalidate();
    }

    @OnClick(R2.id.item_start_stop)
    public void startStop() {
        if (motorDialog != null && motorDialog.isShowing()) return;
        motorDialog = new MotorDialog(this, !isMotorStart, this);
        motorDialog.show();
    }

    @OnClick(R2.id.item_reduce)
    public void reduce() {
        int progress = itemSeekBar.getProgress();
        if (progress - 1 <= 0) progress = 0;
        else progress = progress - 1;
        itemSeekBar.setProgress(progress);
    }

    @OnClick(R2.id.item_add)
    public void plus() {
        int progress = itemSeekBar.getProgress();
        if (progress + 1 >= MAX_WEIGHT - MIN_WEIGHT) progress = MAX_WEIGHT - MIN_WEIGHT;
        else progress = progress + 1;
        itemSeekBar.setProgress(progress);
    }

    @Override
    public void dispatchHandleMessage(@org.jetbrains.annotations.Nullable Message message) {
        if (EmptyUtils.isEmpty(message)) return;
        switch (message.what) {
            case 0x001:
                refreshBallChart();
                refreshCountChart();
                break;
            case 0x002:
                getHandler().postDelayed(() -> {
                    times.add(NormalUtils.dateToString("mm:ss", new Date()));
                    distances.add(new Entry(distances.size(), 300));
                    weights.add(NormalUtils.dateToString("mm:ss", new Date()));
                    countDistances.add(new BarEntry(distances.size(), 300));
                    localEmptyMsg(0x001);
                    localEmptyMsg(0x002);
                }, 800);
                break;
        }
    }

    @Override
    public void onAction(boolean motorStart, boolean confirm) {
        if (confirm) {
            Bundle bundle = new Bundle();
            bundle.putBoolean(ConstantFitness.START_MOTOR, !isMotorStart);
            gotoActivityForResult(MotorStartStopActivity.class, bundle, ConstantFitness.REQUEST_MOTOR_ACTION);
        }
    }

    @Override
    public void onStartTrackingTouch(boolean isCanDrag) {
        CommonUtils.INSTANCE.log("onStartTrackingTouch-----------isCanDrag:" + isCanDrag);

    }

    @Override
    public void onProgressChanged(float progress, float max, boolean fromUser) {
        CommonUtils.INSTANCE.log("onProgressChanged-----------fromUser:" + fromUser + "----------progress:" + progress);
        int progressWeight = (int) progress + MIN_WEIGHT;
        itemWeight.setText(String.valueOf(progressWeight));
    }

    @Override
    public void onStopTrackingTouch(boolean isCanDrag) {
        CommonUtils.INSTANCE.log("onStopTrackingTouch-----------isCanDrag:" + isCanDrag);

    }

    @Override
    public void onSingleTapUp() {
        CommonUtils.INSTANCE.log("onSingleTapUp-----------");

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (ConstantFitness.REQUEST_MOTOR_ACTION == requestCode) {
            isMotorStart = !isMotorStart;
        }
    }
}
